package de.zinulla.moviethek.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

import de.zinulla.common.MoviethekConstants;
import de.zinulla.moviethek.CoverViewActivity;
import de.zinulla.moviethek.R;
import de.zinulla.moviethek.contentprovider.MoviethekContentProvider;
import de.zinulla.moviethek.db.MovieDataSource;
import de.zinulla.moviethek.db.MovieDb;
import de.zinulla.moviethek.db.MoviesTable;

public class DetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> {

	private long id;
	private MovieDataSource datasource;
	private MovieDb movie;
	private static final int REQUEST_CODE = 30;

	public void setId(long id) {
		this.id = id;
	}

//	@Override
//	public void onCreate(Bundle savedInstanceState) {
//		super.onCreate(savedInstanceState);
//	}
//
//	@Override
//	public void onActivityCreated(Bundle savedInstanceState) {
//		super.onActivityCreated(savedInstanceState);
//
//	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.movie_detail, container, false);

		if (id == 0) {
			SharedPreferences settings = getActivity().getSharedPreferences(MoviethekConstants.MOVIE_SP, 0);
			id = settings.getLong(MoviethekConstants.MOVIE_ID, 0);
		}

		datasource = new MovieDataSource(getActivity().getApplicationContext());
		datasource.open();
		movie = datasource.getMovieBySqlId(id);
		ImageView image = (ImageView) view.findViewById(R.id.cover);
		byte[] byteArr = movie.getCover();
		image.setImageBitmap(BitmapFactory.decodeByteArray(byteArr, 0, byteArr.length));
		image.setClickable(true);
		image.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					String coverUrl = movie.getCoverUrl();
					SharedPreferences movieId = getActivity().getApplicationContext().getSharedPreferences(
							MoviethekConstants.COVER_URL_SP, 0);
					SharedPreferences.Editor editor = movieId.edit();

					editor.putString(MoviethekConstants.COVER_URL, coverUrl);
					editor.commit();
					
					Intent i = new Intent(getActivity(), CoverViewActivity.class);
					i.putExtra(MoviethekConstants.COVER_URL, coverUrl);
					startActivityForResult(i, REQUEST_CODE);
				} 
				return false;
			}
		});

		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText(movie.getMovieName());
		title.setClickable(true);
		
		ImageView imdb = (ImageView) view.findViewById(R.id.imdb);
		imdb.setOnClickListener(new View.OnClickListener() {
		
			@Override
			public void onClick(View v) {
				String uri = "imdb:///title/" + movie.getImdbId() + "/";
				if(isUriAvailable(getSherlockActivity(),uri )){
				Intent i = new Intent("android.intent.action.VIEW", 
						Uri.parse(uri)); 
						startActivity(i); 
				} else {
					try {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+"com.imdb.mobile")));
					} catch (android.content.ActivityNotFoundException anfe) {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="+"com.imdb.mobile")));
					}

				}
				
			}
		});

		ImageView media = (ImageView) view.findViewById(R.id.media);
		if(MoviethekConstants.MEDIA_BR.equals(movie.getMedia())){
			media.setBackgroundResource(R.drawable.bluray);
		} else if(MoviethekConstants.MEDIA_BR_3D.equals(movie.getMedia())){
			media.setBackgroundResource(R.drawable.bluray3d);
		}else if(MoviethekConstants.MEDIA_DVD.equals(movie.getMedia())){
			media.setBackgroundResource(R.drawable.dvd);
		}

		TextView actor = (TextView) view.findViewById(R.id.actor);
		actor.setText(movie.getActor());

		TextView plot = (TextView) view.findViewById(R.id.plot);
		plot.setText(movie.getPlot());

		TextView year = (TextView) view.findViewById(R.id.year);
		year.setText(movie.getYear());

		TextView runtime = (TextView) view.findViewById(R.id.runtime);
		runtime.setText(movie.getRuntime() + " Min.");
		datasource.close();
		return view;
	}

	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	public static DetailFragment newInstance(long id) {
		DetailFragment f = new DetailFragment();
		f.setId(id);
		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putLong("id", id);
		f.setArguments(args);

		return f;
	}

	public long getShownId() {
		return id;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		String[] projection = { MoviesTable.COLUMN_ID, MoviesTable.COLUMN_COVER, MoviesTable.COLUMN_MOVIE_NAME, MoviesTable.COLUMN_YEAR, MoviesTable.COLUMN_MEDIA };
		CursorLoader cursorLoader = new CursorLoader(getActivity().getApplicationContext(),
				MoviethekContentProvider.CONTENT_URI, projection, null, null, null);
		return cursorLoader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
//		adapter.swapCursor(data);

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
//		adapter.swapCursor(null);

	}
	
		public static boolean isUriAvailable(Context context, String uri) {
		    Intent test = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
		    return context.getPackageManager().resolveActivity(test, 0) != null;
		}

		
//	    final PackageManager packageManager = context.getPackageManager();
//	    final Intent intent = new Intent(action);
//	    List<ResolveInfo> resolveInfo =
//	            packageManager.queryIntentActivities(intent,
//	                    PackageManager.MATCH_DEFAULT_ONLY);
//	   if (resolveInfo.size() > 0) {
//	   		return true;
//	   	}
//	   return false;
//	}
}
